<template>
  <div class="student-response">
    <header class="header">
      <span class="tip"
        >{{
          STATUS_ENUM.find(
            item => item.id === currentStudent?.teacher_correct
          )?.['name']
        }}
        |
        {{
          formatNum(currentStudent?.score_rate) ||
          formatNum(currentStudent?.score_rate) ||
          0
        }}%</span
      >
    </header>
    <main>
      <DrawingBoard ref="drawingBoard" :current-mode="currentMode">
        <template #content>
          <div class="content" ref="wrapperRef">
            <img
              v-if="handleUrl.length"
              ref="imgRef"
              :style="getStyle"
              :src="handleUrl[currentImg - 1]"
            />

            <div
              class="response-content"
              v-else-if="handleResponse"
              v-html="handleResponse"
              style="color: #fff; font-size: 20px"
            ></div>
          </div>
        </template>
      </DrawingBoard>
    </main>
    <footer>
      <img-tools
        v-if="handleUrl.length"
        @change-img="changeImg"
        :is-fixed="true"
        :current="currentImg"
        :total="handleUrl.length"
        :content="currentStudent"
        @rotate="rotateImg"
        @scale="scaleImg"
        @recover="recoverImg"
      />
      <student-tools
        :is-fixed="true"
        :content="currentStudent"
        :total="allStudentList.length"
        @change-student="changeStudent"
      />
      <button @click="closePage" class="close-btn">
        <span class="close-btn__icon"></span>
        <span class="close-btn__desc">关闭</span>
      </button>
      <button @click="closePage" class="close-btn">
        <span class="close-btn__icon"></span>
        <span class="close-btn__desc">关闭</span>
      </button>
    </footer>
    <SketchpadTools @draw="draw" @revert="revert"></SketchpadTools>
  </div>
</template>
<script setup>
import { formatNum } from '@/utils/common'
import { ref, reactive, onMounted, computed } from 'vue'
import { getResponseOfDetail } from '@/apis/comment/index.js'
import { useComment } from '@/stores/comment'
import ImgTools from './response/ImgTools.vue'
import StudentTools from './student-compare/StudentTools.vue'
import SketchpadTools from './components/SketchpadTools.vue'
import DrawingBoard from './components/DrawingBoard.vue'
import { useRouter, useRoute } from 'vue-router'
import { STATUS_ENUM } from './constant'
const router = useRouter()
const route = useRoute()
const drawingBoard = ref()
const currentImg = ref(1)
const currentStudent = ref(null)
const currentIndex = ref(0)
const imgStyle = reactive({
  rotate: 0,
  scale: 1
})
const studentList = ref([])
const allStudentList = ref([])
const imgRef = ref(null)
const wrapperRef = ref(null)
const currentMode = ref('select')

const handleUrl = computed(() => {
  const children = currentStudent.value?.children_response || []
  const childUrl = children
    .map(item => JSON.parse(item.response_url))
    .filter(item => item.length)
  if (currentStudent.value && (currentStudent.value.response_url || childUrl)) {
    const url = JSON.parse(currentStudent.value.response_url)?.length
      ? JSON.parse(currentStudent.value.response_url)
      : childUrl
        ? childUrl
        : ''
    console.log('查看url', url)
    return url || []
  }
  return []
})

const handleResponse = computed(() => {
  const children = currentStudent.value?.children_response || []
  const childRes = children.map(
    (item, index) => `(${index + 1})${JSON.parse(item.response)}`
  )
  if (currentStudent.value && (currentStudent.value.response || childRes)) {
    const res = JSON.parse(currentStudent.value.response)?.length
      ? JSON.parse(currentStudent.value.response)
      : childRes
        ? childRes
        : ''
    return res || []
  }
  return []
})

const getResponseDetail = async () => {
  const { data } = await getResponseOfDetail({
    task_id: route.query.task_id,
    class_id: route.query.class_id,
    question_id: route.query.question_id,
    class_type: route.query.class_type
  })
  allStudentList.value = data || []
  studentList.value = data || []
}

const getStyle = computed(() => {
  if (imgRef.value) {
    const currentImgRef = imgRef.value
    const width = currentImgRef.width
    const height = currentImgRef.height
    const wrapperHeight = wrapperRef.value.clientHeight
    const wrapperWidth = wrapperRef.value.clientWidth
    const ratio = width / height
    let renderWidth = ''
    if (width > height) {
      // 旋转90/270
      if (imgStyle.rotate % 180 === 90 || imgStyle.rotate % 180 === -90) {
        renderWidth = wrapperHeight + 'px'
        return `transform: rotate(${imgStyle.rotate}deg) scale(${imgStyle.scale}); width: ${renderWidth};`
      } else {
        return `transform: rotate(${imgStyle.rotate}deg) scale(${imgStyle.scale}); width: 100%;`
      }
    } else {
      // 旋转90/270
      if (imgStyle.rotate % 180 === 90 || imgStyle.rotate % 180 === -90) {
        renderWidth = wrapperWidth * ratio + 'px'
        return `transform: rotate(${imgStyle.rotate}deg) scale(${imgStyle.scale}); width: ${renderWidth};`
      } else {
        renderWidth = wrapperHeight * ratio + 'px'
        return `transform: rotate(${imgStyle.rotate}deg) scale(${imgStyle.scale}); width: 100%;`
      }
    }
  } else {
    return `transform: rotate(${imgStyle.rotate}deg) scale(${imgStyle.scale});`
  }
})

const scaleImg = scale => {
  if (scale === 'enlarge') {
    imgStyle.scale = parseFloat(imgStyle.scale.toFixed(1)) + 0.2
  } else {
    if (parseFloat(imgStyle.scale.toFixed(1)) > 0.2) {
      imgStyle.scale = parseFloat(imgStyle.scale.toFixed(1)) - 0.2
    }
  }
}

const rotateImg = direction => {
  if (direction === 'left') {
    imgStyle.rotate -= 90
  } else {
    imgStyle.rotate += 90
  }
}

const recoverImg = () => {
  imgStyle.rotate = 0
  imgStyle.scale = 1
}

const changeImg = page => {
  if (page === 'next') {
    currentImg.value += 1
  } else {
    currentImg.value -= 1
  }
}
const closePage = () => {
  router.go(-1)
}

const changeStudent = item => {
  const total = allStudentList.value.length
  if (item === 'next') {
    currentIndex.value = Math.abs(currentIndex.value + 1) % total
  } else {
    currentIndex.value = (currentIndex.value - 1 + total) % total
  }
  currentStudent.value = allStudentList.value[currentIndex.value]
  currentImg.value = 1
}

const draw = type => {
  currentMode.value = type
  drawingBoard.value && drawingBoard.value.draw(type)
}

const revert = type => {
  drawingBoard.value && drawingBoard.value.revert(type)
}

onMounted(async () => {
  await getResponseDetail()
  currentStudent.value = studentList.value[0]
})
</script>
<style lang="less" scoped>
.student-response {
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background: rgba(25, 43, 42, 1);
  width: 100vw;
  height: 100vh;
  .header {
    display: flex;
    justify-content: space-between;
    padding: 32px;
    align-items: center;

    .tip {
      color: rgba(255, 90, 80, 1);
      font-size: 20px;
      font-weight: 700;
    }

    .label {
      label {
        display: inline-block;
        margin-left: 24px;
        height: 72px;
        width: 72px;
      }

      .excellent {
        background: url('@/assets/images/comment/excellent-big.png') no-repeat
          center/cover;
      }

      .typical {
        background: url('@/assets/images/comment/typical-big.png') no-repeat
          center/cover;
      }
    }
  }

  main {
    flex: 1;
    box-sizing: border-box;
    padding: 0 58px 180px 58px;
    height: 100%;
    .content {
      background: rgba(217, 217, 217, 0.42);
      overflow: auto;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }

      .response-content {
        font-size: 24px;
      }
    }
  }

  footer {
    width: 100%;
    position: fixed;
    bottom: 0;
    display: flex;
    justify-content: space-between;

    .close-btn {
      width: 64px;
      height: 64px;
      border-radius: 12px;
      display: inline-flex;
      flex-direction: column;
      background: #fff;
      justify-content: center;
      align-items: center;
      border: none;
      cursor: pointer;

      &__icon {
        display: inline-block;
        width: 34px;
        height: 34px;
        background: url('@/assets/images/comment/close-page.png') no-repeat
          center/cover;
      }

      &__desc {
        color: rgba(255, 90, 80, 1);
      }
    }
  }
}
</style>
